﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;
using System.Web.Hosting;

namespace SecurityModule
{
    abstract class SimpleWorkflow : IWorkflow
    {
        public string Path { get; set; }
        public string Verb { get; set; }

        private bool Condition(HttpContext context)
        {
            return context.Request.FilePath.Equals(Path, StringComparison.OrdinalIgnoreCase) && context.Request.RequestType == Verb;
        }
        public void PreProcess(HttpContext context)
        {
            if (Condition(context))
                PreProcessImplementation(context);
        }
        public void PostProcess(HttpContext context)
        {
            if (Condition(context))
                PostProcessImplementation(context);
        }

        public abstract void PreProcessImplementation(HttpContext context);
        public abstract void PostProcessImplementation(HttpContext context);

        protected void AddToForm(HttpRequest request, Dictionary<string, string> values)
        {
            var form = request.Form;

            var type = form.GetType();

            var prop = type.GetProperty("IsReadOnly", BindingFlags.Instance
                | BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);

            prop.SetValue(form, false, null);

            foreach (var value in values)
            {
                request.Form.Add(value.Key, value.Value);
            }
        }

        public static readonly string SecurityServiceDownMsg = "Can't perform the operation because of a technical error related to security";

        public static string GetEmailTemplatePath(string name)
        {
            // ReSharper disable AssignNullToNotNullAttribute
            return System.IO.Path.Combine(HostingEnvironment.MapPath("~/EmailTemplates/Module/"), name + ".html");
            // ReSharper restore AssignNullToNotNullAttribute
        }
    }
}
